package com.books.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.*;

/**
 * @ClassName: JsoupHtmlUtil
 * @Description:
 * @Date: 2023/12/4 15:04
 * @author: <chuanwan.zhu@haohanit.com.cn>
 * @version: 1.0
 * @since: JDK 1.8
 */
@Slf4j
@Data
public class JsoupHtmlUtil {
    public static Map<String, Object> catalogList(String url) {
        Map<String, Object> map = new HashMap<>();
        try {
            Document doc = Jsoup.connect(url).timeout(5000).get();
            System.out.println("===");
            Elements elementsTitle = doc.select(".info > h2");
            map.put("title", elementsTitle.get(0).text());
            List<String> catalogList = new ArrayList<>();
            Elements elementsDiv = doc.select(".listmain > dl > dd > a");
            LinkedHashMap<String, String> catalogMap = new LinkedHashMap<>();
//            for (int i = elementsDiv.size() - 1; i >= 0; i--) {
//                catalogMap.put(elementsDiv.get(i).attr("href"), elementsDiv.get(i).text());
////                System.out.println(elementsDiv.get(i).text() + "=====" + elementsDiv.get(i).attr("href"));
//            }
            int i = 1;
            for (Element e : elementsDiv) {
                if (i > 12) {
                    System.out.println(e.text() + "=====" + e.attr("href"));
                    catalogMap.put(e.attr("href"), e.text());
                }
                i++;
            }
            map.put("catalogMap", catalogMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static String getContent(String url) {
        StringBuilder builder = new StringBuilder();
        try {
            Document doc = Jsoup.connect(url).timeout(5000).get();
            Elements elements = doc.select("#content");
            for (Element e : elements) {
                builder.append(e.text());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder.toString();
    }

    private static Element getElement(Elements elements, String id) {
        for (Element e : elements) {
            if (e.attr("data-id").equals(id)) {
                return e;
            }
        }
        return null;
    }
}
